package com.wawayaya.bookreader.ViewPages;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wawayaya.bookreader.DefaultSettings;
import com.wawayaya.bookreader.Imutualaction;
import com.wawayaya.bookreader.bean.IntDouble;
import com.wawayaya.bookreader.bean.Pagedata;
import com.wawayaya.bookreader.bean.Pagesdata;
import com.wawayaya.util.Devicescreenbasicinfo;
import com.wawayaya.util.NetUtils;
import com.wawayaya.util.TLog;

import wawayaya.kids_iread.R;


public class NewViewPagerAdapter extends PagerAdapter {

	
	public Context m_ct = null;
	public LayoutInflater mInflater = null;
	private Devicescreenbasicinfo m_dsi = null;
	
	//protected RelativeLayout.LayoutParams mBookPageParams = null;
	//protected RelativeLayout.LayoutParams mViewPagerParams = null;
	
	private int m_ibookpagesCount = 0;
	private int m_icontentPageCount = 0;
	private int m_iquizpagescount = 0;
    private String m_quizurl = null;
	private Pagesdata[] m_psds = null;
	private Pagesdata m_psdcurrent = null;
	private Imutualaction m_mutualactioncallback = null;
	private int m_inetid = 0;
	private int m_ibookid = 0;
	private boolean m_bhasquiz = false;
	private int m_ikokcolor = Color.RED;
	
	private NewContainerView[] m_view = null;
	private NewQuizView[] m_quizviews = null;
	private int m_irealviewwidth = ViewPager.LayoutParams.MATCH_PARENT;
	private int m_irealviewHeight = ViewPager.LayoutParams.MATCH_PARENT;
	private float m_fratio = 1.0f;
	private int m_idecoderatio = 1;
	private int m_idecoderatiofore = 1;
	private int m_iscreenwidth = 0;
	private int m_iscreenheight = 0;
	private int[] m_iwaitanimresid = null;
	private BitmapDrawable[] m_bdwaitanim = null;
	private boolean m_bookdownloaderrorresolved = true;
	private int m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;
	private int m_inowpagepos = -1;
	private int mBookOriginalW;
	private int mBookOriginalH;
	
	public NewViewPagerAdapter(Context context,
			int ibookpagescount, int icontentpagescount, /*int iquizpagescount,*/
			Pagesdata[] psds,
			Imutualaction callback, 
			int inetid, int ibookid, 
			int ikokocolor, 
			Devicescreenbasicinfo dsi,
			int[] iwaitanimresid, BitmapDrawable[] bdwaitanim,
			int ireadtype,
            String quizurl) {
		m_ct = context;
        m_dsi = dsi;  
		mInflater = LayoutInflater.from(m_ct);
		m_ibookpagesCount = ibookpagescount;
		m_icontentPageCount = icontentpagescount;
        m_quizurl = quizurl;
        if (!TextUtils.isEmpty(m_quizurl)) {
            m_iquizpagescount = 1;
            //m_iquizpagescount = iquizpagescount;
        }
		m_psds = psds;
		m_mutualactioncallback = callback;
		m_inetid = inetid;
		m_ibookid = ibookid;
		m_bhasquiz = m_iquizpagescount > 0;
		m_ikokcolor = ikokocolor;
		m_iwaitanimresid = iwaitanimresid;
		m_bdwaitanim = bdwaitanim;
		m_ireadtype = ireadtype;
				
		initcurrentpagesdata();
		IntDouble idu = getbookpagebackgroundimgsize();
		int ibookcoordinatewidth = idu.m_ival1;
		int ibookcoordinateheight = idu.m_ival2;
		mBookOriginalW = ibookcoordinatewidth;
		mBookOriginalH = ibookcoordinateheight;
 		int ibkgWidth = idu.m_ival1;
		int ibkgHeight = idu.m_ival2;
		idu = getforegroundimgsize();
		int ifrgWidth = null != idu ? idu.m_ival1 : ibkgWidth;
		int frgHeight = null != idu ? idu.m_ival2 : ibkgHeight;
		
		m_iscreenwidth = m_dsi.m_iScreenWidth;
		m_iscreenheight = m_dsi.m_iScreenHeight;
		try {				
			m_fratio = DefaultSettings.getToScreenRatio(m_iscreenwidth, m_iscreenheight,
							ibookcoordinatewidth, ibookcoordinateheight, 
							ibkgWidth, ibkgHeight);
			m_irealviewwidth = (int)(ibookcoordinatewidth * m_fratio + 0.499);
			m_irealviewHeight = (int)(ibookcoordinateheight * m_fratio + 0.499);
			float fbkw = (float)ibkgWidth / (float)m_iscreenwidth * m_dsi.m_fscreendensity;
			float fbkh = (float)ibkgHeight / (float)m_iscreenheight * m_dsi.m_fscreendensity;
			if((int)fbkw >= 2 || (int)fbkh >= 2){
				m_idecoderatio = Math.min((int) fbkw, (int) fbkh);
			}
			else if(fbkw - 1.8 < 0.01 || fbkh - 1.8 < 0.01) {
				m_idecoderatio = 2;
			}
			float ffrw = ((float)ifrgWidth / (float)m_iscreenwidth);
			float ffrh = ((float)frgHeight / (float)m_iscreenheight);
			m_idecoderatiofore = (int) Math.min(ffrw, ffrh);
		} catch (Exception e) {
		}
		// demo code, should update later		
		
		m_view = new NewContainerView[m_ibookpagesCount];
		for(int i = 0 ; i < m_ibookpagesCount; i++) {
			m_view[i] = null;
		}
		
		if(m_iquizpagescount > 0) {
			m_quizviews = new NewQuizView[m_iquizpagescount];
			for(int i = 0 ; i < m_iquizpagescount; i++) {
				m_quizviews[i] = null;
			}
		}
	}

	@Override
	public synchronized void destroyItem(ViewGroup container, int position, Object object) {
		if(null != m_view && position < m_view.length) {
			m_view[position] = null;
		}
		try{
			if(null != object && position < m_ibookpagesCount) {
				((NewContainerView)object).tostopanim();
				((NewContainerView)object).recycle();
			}
			else{
				((NewQuizView)object).recycle();
			}
			((ViewPager)container).removeView((NewContainerView)object);
		}catch(Exception e){
		}
	}
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		m_bookdownloaderrorresolved = NetUtils.checkNetwork(m_ct);
		if(null != m_view && position < m_view.length && null != m_view[position]) {
			m_view[position].setbookdownloaderrorresolved(m_bookdownloaderrorresolved);
			return m_view[position];
		}
		if(null != m_view && position >= m_view.length &&
				null != m_quizviews && 
				(m_view.length - position) < m_quizviews.length && null != m_quizviews[m_view.length - position]){
			m_quizviews[m_view.length - position].refreshinformation();
			return m_quizviews[m_view.length - position];
		}
		
		ViewPager.LayoutParams params = new ViewPager.LayoutParams();
		params.width = m_irealviewwidth;
		params.height = m_irealviewHeight;		
		//params.width = m_iscreenwidth;
		//params.height = m_iscreenheight;		

		CustomViewPager cvp = (CustomViewPager)container;
		if(position < m_view.length) {
			NewContainerView Item = (NewContainerView)mInflater.inflate(R.layout.reader_pageradapterview, null);
			Item.setwaitanimresource(m_iwaitanimresid, m_bdwaitanim);
			Item.setratio(m_fratio, m_idecoderatio, m_dsi.m_fscreendensity, mBookOriginalW, mBookOriginalH,(m_iscreenwidth - m_irealviewwidth) / 2,
                    (m_iscreenheight - m_irealviewHeight) / 2);
			Item.setbooknetid(m_inetid);
			Item.setbookid(m_ibookid);
			Item.findviews(m_mutualactioncallback, m_ikokcolor, m_dsi, m_ireadtype, getpagedata(position));
			//加载每页数据
			Item.setposition(position, getpagedata(position), (m_iscreenwidth - m_irealviewwidth) / 2, (m_iscreenheight - m_irealviewHeight) / 2);
			m_view[position] = Item;
			m_view[position].setbookdownloaderrorresolved(m_bookdownloaderrorresolved);			
			cvp.addView(Item, params);
			m_view[position].recordselectedpage(position == m_inowpagepos ? true : false);
			return Item;
		}

        NewQuizView qv = (NewQuizView)mInflater.inflate(R.layout.reader_quizview, null);
		cvp.addView(qv, params);
        qv.findviews();
		qv.setmutualactioncallback(m_mutualactioncallback);
        if (!TextUtils.isEmpty(m_quizurl)) {
            qv.setquizurls(new String[]{m_quizurl});
        }
        qv.refreshinformation();
		m_quizviews[m_view.length - position] = qv;
		return qv;
    }

	@Override
	public int getCount() {
		return m_ibookpagesCount + m_iquizpagescount;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	public  void updatepagesdata(Pagesdata psd, int idx, int inowpagepos, boolean bautokok) {
		if(idx >= 0 && idx < m_psds.length && null != psd){
			m_psds[idx] = psd;
			try{
				if(m_psds[idx].pageisin(inowpagepos)) {
					m_view[inowpagepos].setposition(inowpagepos, getpagedata(inowpagepos), (m_iscreenwidth - m_irealviewwidth) / 2, (m_iscreenheight - m_irealviewHeight) / 2, bautokok);
				}
				if(inowpagepos - 1 >= 0 && m_psds[idx].pageisin(inowpagepos - 1)) {
					m_view[inowpagepos - 1].setposition(inowpagepos -1, getpagedata(inowpagepos - 1), (m_iscreenwidth - m_irealviewwidth) / 2, (m_iscreenheight - m_irealviewHeight) / 2);
				}
				if(inowpagepos + 1 > 0 && m_psds[idx].pageisin(inowpagepos + 1)) {
					m_view[inowpagepos + 1].setposition(inowpagepos + 1, getpagedata(inowpagepos + 1), (m_iscreenwidth - m_irealviewwidth) / 2, (m_iscreenheight - m_irealviewHeight) / 2);
				}
			}catch(Exception e){
			}
		}
	}
	
	public void informbookdownloaderrorresolved(boolean bresolved) {
		m_bookdownloaderrorresolved = bresolved;
		if(null != m_view){
			for(NewContainerView cv : m_view){
				if(null != cv) {
					cv.setbookdownloaderrorresolved(m_bookdownloaderrorresolved);
				}
			}
		}
	}
	
/*	public void setLayoutInfo(RelativeLayout.LayoutParams BookPageParams, RelativeLayout.LayoutParams ViewPagerParams) {
		if(BookPageParams!= null) {
			mBookPageParams = new RelativeLayout.LayoutParams(BookPageParams);
		}
		if(ViewPagerParams != null) {
			mViewPagerParams = new RelativeLayout.LayoutParams(ViewPagerParams);
		}
	}*/
	
	public NewBookPageView getbookpageview(int iidx) {
		try{
			if(iidx >= 0 && iidx < m_view.length){
				return m_view[iidx].getbookapgeview();
			}
		}catch(Exception e){
		}		
		return null;
	}
	
	public synchronized void recordselectedpage(int iidx){
		m_inowpagepos = iidx;
		try{
			if(null != m_view && iidx >= 0 && iidx < m_view.length){
				for(int i = 0; i < m_view.length; i++) {
					if(null != m_view[i]){
						m_view[i].recordselectedpage(i == iidx ? true : false);
					}
				}
			}
		}catch(Exception e){
		}		
	}
	
	public void tostopwaitinganim() {
		if(null != m_view) {
			for(NewContainerView cv : m_view) {
				if(null != cv) {
					cv.tostopanim();
				}
			}
		}
	}
	
	public void recycle()
	{
		TLog.log("Alan", "ViewPageAdapter.recycle");
		if(m_view != null)
		{
			for(int i = 0; i < m_view.length; i++)
			{
				if(m_view[i] != null)
				{
					m_view[i].closewaitinnerpageloadingtext();
					NewBookPageView bpv = m_view[i].getbookapgeview();
					if(bpv != null)
					{
						bpv.recycle();
					}
				}
			}
		}
		destroyitems();
	}
	
	public NewQuizView getquizview(int iidx){
		try{
			if(iidx - m_view.length < m_quizviews.length){
				return m_quizviews[iidx - m_view.length];
			}
		}catch(Exception e){
		}		
		return null;
	}
	
	public boolean isquizview(int iidx) {
		try{
			if(null != m_view && iidx >= m_view.length && iidx - m_view.length < m_quizviews.length){
				return true;
			}
		}catch(Exception e){
		}
		return false;
	}
/*
	public boolean quitquizview(int inowpagepos){
		if(!isinquizview(inowpagepos)) {
			return false;
		}
		m_quizviews[inowpagepos - m_ibookpagesCount].quitquizonlineview();
		return true;
	}*/
	
	private void destroyitems() {
		if(null != m_view) {
			for(int i = 0; i < m_view.length; i++){
				if(null != m_view[i]){
					try{
						m_view[i].tostopanim();
						m_view[i].recycle();
					}
					catch(Exception e){
					}
				}
				m_view[i] = null;
			}
			m_view = null;
		}
		if(null != m_quizviews) {
			for(int i = 0; i < m_quizviews.length; i++){
				if(null != m_quizviews[i]){
					try{
						m_quizviews[i].recycle();
					}catch(Exception e){
					}
					m_quizviews[i] = null;
				}
			}
			m_quizviews = null;
		}
	}

/*	private boolean isinquizview(int inowpagepos){
		if(!m_bhasquiz){
			return false;
		}
		if(inowpagepos < 0 || inowpagepos < m_ibookpagesCount) {
			return false;
		}
		if(null == m_quizviews || (inowpagepos - m_ibookpagesCount) >= m_quizviews.length || null == m_quizviews[inowpagepos - m_ibookpagesCount]) {
			return false;
		}
		return m_quizviews[inowpagepos - m_ibookpagesCount].isinquizview();
	}*/

	private void initcurrentpagesdata() {
		if(null == m_psdcurrent && null != m_psds){
			for(int i = 0; i < m_psds.length; i++){
				if(null != m_psds[i]) {
					m_psdcurrent = m_psds[i];
					return;
				}
			}
		}
	}
	
	private IntDouble getbookpagebackgroundimgsize(){
		try{
			//return m_psdcurrent.getbookpagebackgroundimgsize();
			return m_psds[0].getbookdefwidthheight();
		}catch(Exception e){
		}
		return null;
	}
	
	private IntDouble getforegroundimgsize(){
		try{			
			//return m_psdcurrent.getforegroundimgsize(m_psdcurrent.getbegininnerpageidx());
			return m_psds[0].getbookdefwidthheight();
		}catch(Exception e){
		}	
		return null;	
	}

	private IntDouble getapplicationscreensize(){	
		try{	
			return m_psdcurrent.getapplicationscreensize(m_psdcurrent.getbegininnerpageidx());		
		}catch(Exception e){
		}	
		return null;
	}
	
	private Pagedata getpagedata(int iinnerpage){
		try{
			if(!m_psdcurrent.pageisin(iinnerpage)) {
				for(int i = 0; i < m_psds.length; i++){
					if(null != m_psds[i] && m_psds[i] != m_psdcurrent) {
						if(m_psds[i].pageisin(iinnerpage)){
							m_psdcurrent = m_psds[i];
							return m_psdcurrent.getpagedata(iinnerpage);
						}
					}
				}
			}
			else{
				return m_psdcurrent.getpagedata(iinnerpage);
			}
		}catch(Exception e){
			TLog.error("ViewPagerAdapter : getpagedata : iinnerpage = " + iinnerpage + " e : " + e);
		}	
		return null;
	}
	
	private String[] getquizurls(){
		try{	
			return m_psdcurrent.getquizurls();
		}catch(Exception e){
		}
		return null;
	}

}
